import * as React from 'react';
import PropTypes from 'prop-types';
import { Form, Field, DatePicker, Select, Balloon } from '@teamix/ui';
import { YunxiaoIcon, ButtonIcon } from '@alife/devops-ui';
import MemberTrigger from 'components/memberTrigger';
import Popup from 'components/popup';
// import PathEllipsis from 'components/pathEllipsis';
import '../index.scss';
import utils from 'utils';
import docs from 'utils/docs';
import dayjs from 'dayjs';
import { repoTypes, repoActionTypes, groupTypes } from './auditConstants';
import intl from '../../../../../../../../../locale';
const { RangePicker } = DatePicker;
const { organization } = window.FORCE;

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    fixedSpan: 12,
  },
};

const allProjectType = repoTypes.join(',');

const allRepoActionType = repoActionTypes.join(',');
const allGroupType = groupTypes.join(',');

const projectTypeData = [
  {
    value: allProjectType,
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.AllOperations',
      defaultMessage: '所有操作',
    }),
  },
  {
    value: 'NEW_REPO',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.CreateADatabase',
      defaultMessage: '新建库',
    }),
  },
  {
    value: 'IMPORT_REPO',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.ImportDatabase',
      defaultMessage: '导入库',
    }),
  },
  {
    value: 'DEL_REPO',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.DeleteADatabase',
      defaultMessage: '删除库',
    }),
  },
  {
    value: 'TRANSFER_REPO',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.TransferDatabase',
      defaultMessage: '转移库',
    }),
  },
  {
    value: 'RESTORE_REPO ',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.RestoreDatabase',
      defaultMessage: '恢复库',
    }),
  },
  {
    value: 'MOD_VISIBILITY',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.OpenAdjustment',
      defaultMessage: '公开性调整',
    }),
  },
  {
    value: 'MOD_MEMBER',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.ModifyLibraryMemberRoles',
      defaultMessage: '修改库成员角色',
    }),
  },
  {
    value: 'REPO_ENABLE_CLD',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.EnableCodeLibraryCloneDownload',
      defaultMessage: '开启代码库克隆下载设置',
    }),
  },
  {
    value: 'REPO_MOD_CLD',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.ModifyCodeLibraryCloneDownload',
      defaultMessage: '修改代码库克隆下载设置',
    }),
  },
  {
    value: 'REPO_DISABLE_CLD',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.DisableCodeLibraryCloneDownload',
      defaultMessage: '关闭代码库克隆下载设置',
    }),
  },
];

const repoTypeData = [
  {
    value: allRepoActionType,
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.AllOperations',
      defaultMessage: '所有操作',
    }),
  },
  { value: 'HTTP_CLONE', label: 'HTTP CLONE' },
  { value: 'SSH_CLONE', label: 'SSH CLONE' },
  { value: 'DOWNLOAD', label: 'DOWNLOAD' },
];

const organizationTypeData = [
  { value: 'ALL', label: '所有操作' },
  { value: 'ADMIN_OPERATIONS', label: '管理员设置' },
  { value: 'ORG_REPO_GROUP_SETTINGS', label: '代码库/组设置' },
  { value: 'ORG_SECURE_CENTER', label: '安全中心设置' },
];

const groupTypeData = [
  {
    value: allGroupType,
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.AllOperations',
      defaultMessage: '所有操作',
    }),
  },
  {
    value: 'NEW_GROUP',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.CreateAGroup',
      defaultMessage: '新建组',
    }),
  },
  {
    value: 'DEL_GROUP',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.DeleteAGroup',
      defaultMessage: '删除组',
    }),
  },
  {
    value: 'TRANSFER_GROUP',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.TransferGroup',
      defaultMessage: '转移组',
    }),
  },
  {
    value: 'RESTORE_GROUP',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.RecoveryGroup',
      defaultMessage: '恢复组',
    }),
  },
  {
    value: 'MOD_VISIBILITY',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.OpenAdjustment',
      defaultMessage: '公开性调整',
    }),
  },
  {
    value: 'MOD_GROUP_MEMBER',
    label: intl.get({
      id: 'code-assets.audit.containers.filterForm.ModifyGroupMemberRoles',
      defaultMessage: '修改组成员角色',
    }),
  },
];

const maxTagPlaceholder = (selectedValues, totalValues) => {
  const trigger = <span>{`${selectedValues.length}/${totalValues.length}`}</span>;
  const labels = selectedValues.map((obj) => obj.label);
  return <Balloon.Tooltip trigger={trigger}>{labels.join(', ')}</Balloon.Tooltip>;
};
const NO_GROUP_TEXT = intl.get({
  id: 'code-assets.audit.containers.filterForm.DoNotSelectACode',
  defaultMessage: '不选择代码组',
});

export default class FilterForm extends React.Component {
  static propTypes = {
    tabKey: PropTypes.string,
    pageSize: PropTypes.string,
    getParamsData: PropTypes.func,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
  }

  componentDidMount() {
    this.onGroupSearch();
    this.onProjectSearch();
  }

  // 搜索代码库得到的结果
  onProjectSearch = (search) => {
    this.props.getProjectOrGroupData('project', search);
  };

  onGroupSearch = (search) => {
    this.props.getProjectOrGroupData('group', search);
  };

  onMemberChange = (value) => {
    this.props.setTBUserData(value);
  };

  onEntityChange = (value) => {
    this.props.setEntityUserData(value);
  };

  onResetClick = () => {
    const { tabKey } = this.props;
    this.props.setClearData(tabKey);
  };

  onRangePickerOk = (value) => {
    this.props.getDateData(value);
  };

  onDateChange = (value) => {
    this.props.setDateData(value);
  };

  onTypeChange = (value) => {
    this.props.setTypeData(value);
  };

  onAuditTypeFilterChange = (value) => {
    this.props.setTypeFilterData(value);
  };

  onRepoChange = (value) => {
    this.props.setRepoData(value);
    if (value.length === 0) {
      this.onProjectSearch();
    }
  };

  onGroupChange = (value) => {
    if (value.length === 0) {
      this.onGroupSearch();
    }
    this.props.resetProjects();
    this.props.setGroupData(value);
    this.onProjectSearch();
  };

  getGroupLabel = (path, id) => {
    if (Number(id) === Number(organization.namespace_id)) {
      return NO_GROUP_TEXT;
    } else {
      return path.includes('/') ? utils.getGroupPath(path) : path;
    }
  };

  getGroupOptions = () => {
    const { groups } = this.props;

    const arr = [
      {
        label: intl.get({
          id: 'code-assets.audit.containers.filterForm.LastUpdated',
          defaultMessage: '最近更新',
        }),
        children: [],
      },
    ];

    groups.forEach((p) => {
      const label = this.getGroupLabel(p.path_with_namespace, p.id);
      if (label === NO_GROUP_TEXT) {
        arr.unshift({
          value: p.id,
          label,
        });
      } else {
         const index = arr.findIndex(
            (item) =>
              item.label ===
              intl.get({
                id: 'code-assets.audit.containers.filterForm.LastUpdated',
                defaultMessage: '最近更新',
              }),
          );
        arr[index].children.push({
          value: p.id,
          label,
        });
      }
    });
    return arr;
  };

  disabledDate = (date) => {
    return (
      date && date.valueOf() < dayjs(dayjs().format('YYYY-MM-DD')).subtract(3, 'month').valueOf()
    );
  };

  render() {
    const { tabKey, paramsData } = this.props;
    const { tb_user_ids, type, project_id, group_id, range, audit_filter_type } = paramsData;

    let typeDatasource;
    if (tabKey === 'project') {
      typeDatasource = projectTypeData;
    }
    if (tabKey === 'repo') {
      typeDatasource = repoTypeData;
    }
    if (tabKey === 'group') {
      typeDatasource = groupTypeData;
    }
    if (tabKey === 'organization') {
      typeDatasource = organizationTypeData;
    }
    return (
      <Popup
        size="large"
        trigger={<ButtonIcon text name="filter-line" />}
        followTrigger
        triggerType="click"
        placement="br"
        className="audit-popup"
        footer={
          <Form.Item style={{ marginBottom: 0 }}>
            <Form.Reset
              text
              type="primary"
              style={{ border: 0 }}
              onClick={this.onResetClick}
              toDefault
            >
              <YunxiaoIcon type="delete-line" />
              {intl.get({
                id: 'code-assets.audit.containers.filterForm.ClearAllFilterConditions',
                defaultMessage: '清除所有筛选条件',
              })}
            </Form.Reset>
          </Form.Item>
        }
      >
        <Form {...formItemLayout} labelTextAlign="left">
          <Form.Item
            label={intl.get({
              id: 'code-assets.audit.containers.filterForm.Operator',
              defaultMessage: '操作人',
            })}
          >
            <div
              className="audit-popup-opcontainer"
              ref={(o) => {
                this.opcontainer = o;
              }}
            >
              <MemberTrigger
                onChange={this.onMemberChange}
                value={tb_user_ids}
                container={() => this.opcontainer}
                noMore
                multiple
                isInviteUrl
              />
            </div>
          </Form.Item>
          <Form.Item
            label={
              <div>
                {intl.get({
                  id: 'code-assets.audit.containers.filterForm.OperationDate',
                  defaultMessage: '操作日期',
                })}

                <Balloon
                  // popupContainer={(trigger) => trigger.parentNode} // 加了z-index会被Tab高亮覆盖，所以不加
                  trigger={
                    <ButtonIcon
                      text
                      name="question-line"
                      size="xs"
                      style={{ marginTop: '-2px', display: 'inline-block' }}
                    />
                  }
                  align="t"
                  closable={false}
                >支持查看最近 1 个月的操作日志，如需查看更多历史请提交
                  <a href={docs('log-limit')} target="_blank" rel="noreferrer">
                    {intl.get({
                      id: 'code-assets.audit.containers.filterForm.TicketApplication',
                      defaultMessage: '工单申请',
                    })}
                  </a>
                </Balloon>
              </div>
            }
          >
            <RangePicker
              followTrigger
              popupAlign="tr br"
              // defaultValue={range}
              value={range}
              onOk={this.onRangePickerOk}
              onChange={this.onDateChange}
              disabledDate={this.disabledDate}
            />
          </Form.Item>
          <Form.Item
            label={intl.get({
              id: 'code-assets.audit.containers.filterForm.Operation',
              defaultMessage: '操作',
            })}
          >
            <Select
              mode="single"
              followTrigger
              dataSource={typeDatasource}
              value={tabKey === 'organization' ? audit_filter_type : type}
              onChange={
                tabKey === 'organization' ? this.onAuditTypeFilterChange : this.onTypeChange
              }
            />
          </Form.Item>
          {(tabKey === 'project' || tabKey === 'group') ? (
            <Form.Item
              label={intl.get({
                id: 'code-assets.audit.containers.filterForm.CodeGroup',
                defaultMessage: '代码组',
              })}
            >
              <Select
                mode="multiple"
                showSearch
                followTrigger
                value={group_id}
                maxTagCount={4}
                placeholder={intl.get({
                  id: 'code-assets.src.utils.locale.EnterACodeGroupName',
                  defaultMessage: '请输入代码组名以搜索',
                })}
                dataSource={this.getGroupOptions()}
                onSearch={this.onGroupSearch}
                onChange={this.onGroupChange}
                maxTagPlaceholder={maxTagPlaceholder}
              />
            </Form.Item>
          ) : null}

          {tabKey === 'project' || tabKey === 'repo' ? (
            <Form.Item
              label={intl.get({
                id: 'code-assets.audit.containers.filterForm.CodeBase',
                defaultMessage: '代码库',
              })}
              style={{ marginBottom: 0 }}
            >
              <Select
                mode="multiple"
                showSearch
                followTrigger
                value={project_id}
                maxTagCount={4}
                placeholder={intl.get({
                  id: 'code-assets.src.utils.locale.EnterACodeLibraryName.1',
                  defaultMessage: '请输入代码库名以搜索',
                })}
                dataSource={[
                  {
                    label: intl.get({
                      id: 'code-assets.audit.containers.filterForm.LastUpdated',
                      defaultMessage: '最近更新',
                    }),
                    children: this.props.projects.map((p) => ({
                      value: p.id,
                      label: p.path_with_namespace.includes('/')
                        ? utils.getGroupPath(p.path_with_namespace)
                        : p.path_with_namespace,
                    })),
                  },
                ]}
                onSearch={this.onProjectSearch}
                onChange={this.onRepoChange}
                maxTagPlaceholder={maxTagPlaceholder}
              />
            </Form.Item>
          ) : null}
        </Form>
      </Popup>
    );
  }
}
